<?php

namespace app\controller\admin\cnf;

use core\controller\AdminBase;
use app\bll\Hook as BllHook;
use support\View;
use app\bll\Plugin as Bllplugin;
use app\bll\ComponentEvent as BllComponentEvent;
use Exception;
use app\bll\HookEvent as BllHookEvent;

class Hook extends AdminBase
{
    public function index()
    {
        $bllHook = new BllHook();
        $hooks   = $bllHook->paginator(
            title: request()->get('title', ''),
            ident: request()->get('ident', ''),
            plugin: request()->get('plugin', ''),
        );

        $bllPlugin = new Bllplugin();
        $plugins = $bllPlugin->select();

        View::assign('plugins', array_column($plugins, null, 'ident'));
        View::assign('hooks', $hooks);
        return $this->view();
    }

    /**
     * 触发事件的方法，根据请求类型执行不同操作
     * 如果是 POST 请求，尝试添加钩子事件数据；如果是其他请求，获取组件事件数据并渲染视图
     *
     * @return mixed 返回操作结果，可能是错误信息、成功信息或渲染后的视图
     */
    public function triggerEvent()
    {
        // 检查请求是否为 POST 请求
        $bllHookEvent = new BllHookEvent();
        if (request()->isPost()) {
            try {
                // 获取 POST 请求的数据
                $data = request()->post();
                // 创建 BllHookEvent 类的实例

                // 调用 BllHookEvent 类的 add 方法添加数据
                $bllHookEvent->add($data);
            } catch (Exception $ex) {
                return $this->error($ex->getMessage());
            }
            return $this->success();
        } else {
            $bllComponentEvent = new BllComponentEvent();
            $events            = $bllComponentEvent->cascader();

            $hookevents = $bllHookEvent->select(request()->get('hookid'));

            // 将获取到的事件数据分配给视图
            View::assign('events', $events);
            View::assign('hookevents', $hookevents);

            // 渲染视图，不使用框架布局
            return $this->view(frame: false);
        }
    }

    public function deleteEvent()
    {
        try {
            $bllHookEvent = new BllHookEvent();
            $bllHookEvent->delete(request()->get('id'));
        } catch (Exception $ex) {
            return $this->error($ex->getMessage());
        }
        return $this->success();
    }
}
